package com.shop.cereshop.app.service.feedback.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.cereshop.app.dao.feedback.FeedbackDAO;
import com.shop.cereshop.app.service.feedback.FeedbackImageService;
import com.shop.cereshop.app.service.feedback.FeedbackService;
import com.shop.cereshop.commons.constant.FeedbackConstant;
import com.shop.cereshop.commons.domain.feedback.Feedback;
import com.shop.cereshop.commons.domain.feedback.FeedbackImage;
import com.shop.cereshop.commons.param.feedback.SubmitFeedbackDTO;
import com.shop.cereshop.commons.utils.EmptyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: TODO
 * @author lx
 * @date 2025/11/19 09:53
 * @version 1.0
 */
@Service
public class FeedbackServiceImpl extends ServiceImpl<FeedbackDAO, Feedback> implements FeedbackService {

    @Autowired
    private FeedbackDAO feedbackDAO;

    @Autowired
    private FeedbackImageService feedbackImageService;

    @Override
    public int submitFeedback(SubmitFeedbackDTO param) {
        // 1. 先保存反馈记录
        Feedback feedback = new Feedback();
        feedback.setUserId(param.getUserId());
        feedback.setUserType(param.getUserType());
        feedback.setContent(param.getContent());
        feedback.setState(FeedbackConstant.FeedbackState.PENDING);
        LocalDateTime now = LocalDateTime.now();
        feedback.setCreateTime(now);
        feedback.setUpdateTime(now);

        // 使用save方法确保主键能正确回填到实体对象中
        int saved = feedbackDAO.insert(feedback);

        // 2. 如果保存成功且有图片，则保存图片记录并关联反馈ID
        if (saved > 0 && !EmptyUtils.isEmpty(param.getImageList())) {
            List<FeedbackImage> feedbackImages = new ArrayList<>();
            for (String image : param.getImageList()) {
                FeedbackImage feedbackImage = new FeedbackImage();
                feedbackImage.setImageUrl(image);
                feedbackImage.setFeedbackId(feedback.getFeedbackId());
                feedbackImages.add(feedbackImage);
            }
            feedbackImageService.saveBatch(feedbackImages);
        }

        return saved;
    }
}
